package com.gt.notify;

import com.gt.service.projectJsdebug.ProjectJsdebugService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 定时邮件通知
 * 类上带有@Configuration的类，等同于spring的XML配置文件，
 *好处是使用Java代码可以检查类型安全。通常还会搭配其他注解来实现不同的需求，如本例中，搭配的@EnableScheduling。
 *在spring-boot中需要在类上添加@EnableScheduling注解来开启对计划任务的支持。
 */
//@Configuration
@EnableScheduling
@Component
public class TimerNotify {
    private static Logger logger = Logger.getLogger(TimerNotify.class);

    @Autowired
    private ProjectJsdebugService projectJsdebugService;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.sender}")
    private String sender;


//    @Scheduled(cron = "0 0/1 * * * ?")
    @Scheduled(cron = "0 0 9-22/4 * * ?")
    public void bugNotify(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info(sdf.format(new Date())+"执行定时通知。");
        Long[] arr = getCurrentTimeFrontAndBack();
        //查询在某一时间段出错误的项目名称和成员信息
        List<HashMap> infoList = projectJsdebugService.querySelectNeedNotify(arr[0], arr[1]);
        if(null != infoList && !infoList.isEmpty()){
            infoList.forEach((HashMap info) ->{
                try {
                    SendEmail.notifyUser2(info.get("project_name").toString(),info.get("member_email").toString(), javaMailSender, sender);
                } catch (Exception e) {
                    logger.error("定时发送邮件异常",e);
                }
            });
        }
    }

    public static Long[] getCurrentTimeFrontAndBack(){
        Calendar can = Calendar.getInstance();
        int year = can.get(Calendar.YEAR);
        int month = can.get(Calendar.MONTH)+1;
        int date = can.get(Calendar.DATE);
        int hour = can.get(Calendar.HOUR_OF_DAY);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long[] arr = new Long[2];
        try {
            sdf.parse(year+"-"+month+"-"+date+" "+hour+":00:00").getTime();
            logger.info("开始时间="+year+"-"+month+"-"+date+" "+(hour-1)+":00:00");
            logger.info("结束时间="+year+"-"+month+"-"+date+" "+hour+":00:00");
            arr[0] = sdf.parse(year+"-"+month+"-"+date+" "+(hour-1)+":00:00").getTime();
            arr[1] = sdf.parse(year+"-"+month+"-"+date+" "+hour+":00:00").getTime();
        }catch (ParseException pe){
            logger.error("时间转换异常",pe);
        }
        return arr;
    }
}
